package com.sgb.kjwl.view.ui.activity.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.swgk.core.util.LogUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySreach5Binding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.sgb.kjwl.model.entity.transport.CategoryItem;
import com.sgb.kjwl.view.ui.fragment.home.SearchNewFragment;
import com.sgb.kjwl.view.ui.fragment.transport.GoodsCarsFragment;
import com.sgb.kjwl.viewmodel.home.SearchModel5;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

/**
 * huwei
 */
public class SearchActivity5 extends AppActivity {
    private static final String TAG = "SearchActivity5";
    private ActivitySreach5Binding binding;
    @Inject
    SearchModel5 viewModel;
    public static final String SEARCH_NAME = "search_name";
    private String[] titles;
    private ArrayList<Fragment> mFragments;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, SearchActivity5.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, String searchName) {
        Intent intent = new Intent();
        intent.setClass(context, SearchActivity5.class);
        intent.putExtra(SEARCH_NAME, searchName);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder().appComponent(appComponent).homeModule(new HomeModule(this)).build().inject(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(SearchActivity5.this, R.layout.activity_sreach5);
        initEtSearchView();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(binding.etView, 0);
                           }
                       },
                200);
    }

    /**
     * 初始化 搜索功能
     */
    private void initEtSearchView() {
        binding.etView.setFocusable(true);
        binding.etView.setFocusableInTouchMode(true);
        binding.etView.requestFocus();
        binding.ivBack.setOnClickListener(this);
        binding.tvSearch.setOnClickListener(this);
        binding.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.etView.setText("");
            }
        });
        binding.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    binding.tvSearchDelete.setVisibility(View.GONE);
                } else {
                    binding.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        binding.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.etView.getText().toString())) {
                        MToast.showToast(SearchActivity5.this, "请输入关键字");
                        return true;
                    }

                    int currentItem = binding.viewPager.getCurrentItem();
                    if (!mFragments.isEmpty() && currentItem < mFragments.size()) {
                        Fragment fragment = mFragments.get(currentItem);
                        if (currentItem == mFragments.size() - 1) {  //物流
                            if (fragment != null && fragment instanceof GoodsCarsFragment) {
                                ((GoodsCarsFragment) fragment).refreshChildView();
                            }
                        } else {
                            if (fragment != null && fragment instanceof SearchNewFragment) {
                                ((SearchNewFragment) fragment).refreshChildView();
                            }
                        }
                        closeKeybord();

                    }
                }
                return false;
            }
        });

        //从上一级进入带入数据进行筛选
        String searchName = getIntent().getStringExtra(SEARCH_NAME);
        if (!TextUtils.isEmpty(searchName)) {
            binding.etView.setText(searchName);
        }
    }


    private String getSearchText() {
        String text = "";
        if (binding != null && binding.etView != null){
            text = TextUtils.isEmpty(binding.etView.getText())?"":binding.etView.getText().toString();
        }
        return text;
    }

    @Override
    protected void init() {
        if (mFragments == null) {
            mFragments = new ArrayList<>();
        }
        viewModel.searchCategory();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
            case R.id.tv_search:
                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    public void showTab(List<CategoryItem> data) {
        if (data == null || data.size() == 0) {
            LogUtil.d(TAG, "showTab failed , response body is null or empty");
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            CategoryItem item = data.get(i);
            if (item == null) {
                LogUtil.d(TAG, "showTab failed , item is null");
                return;
            }
            if (titles == null) {
                titles = new String[data.size()];
            }
            titles[i] = item.getName();
            if (TextUtils.equals(item.getCode(), "company")) {
                mFragments.add(SearchNewFragment.newInstance("company"));
            } else if (TextUtils.equals(item.getCode(), "goods")) {
                mFragments.add(SearchNewFragment.newInstance("goods"));
            } else if (TextUtils.equals(item.getCode(), "recruitment")) {
                mFragments.add(SearchNewFragment.newInstance("recruitment"));
            } else if (TextUtils.equals(item.getCode(), "collect")) {
                mFragments.add(SearchNewFragment.newInstance("collect"));
            } else if (TextUtils.equals(item.getCode(), "rent")) {
                mFragments.add(SearchNewFragment.newInstance("rent"));
            } else if (TextUtils.equals(item.getCode(), "logistics")) {
                mFragments.add(GoodsCarsFragment.newInstance());
            }
        }
        initTabLayout();
    }

    public String getKeyWord() {
        return getSearchText();
    }

    private void initTabLayout() {
        SlidingFragmentPagerAdapter adapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, titles);
        binding.viewPager.setAdapter(adapter);
        binding.viewPager.setOffscreenPageLimit(titles.length - 1);
        binding.tabLayout.setupWithViewPager(binding.viewPager);
    }
}
